﻿using FI.BatchJob.Web.Data;
using FI.BatchJob.Web.Data.Entitities;
using FI.BatchJob.Web.Models;
using FI.BatchJob.Web.QuartzNet;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Quartz;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace FI.BatchJob.Web.Controllers
{

    /// <summary>
    /// Task controller
    /// </summary>
    /// <seealso cref="Microsoft.AspNetCore.Mvc.Controller" />
    [Authorize]
    public class TaskController : Controller
    {

        private readonly SchedulerCenter _scheduler;
        private readonly ApplicationDbContext _dbContext;

        public TaskController(SchedulerCenter schedulerCenter, ApplicationDbContext dbContext)
        {
            _scheduler = schedulerCenter;
            _dbContext = dbContext;

        }
        /// <summary>
        /// 列表页面
        /// </summary>
        /// <returns></returns>
        public IActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 查询数据
        /// </summary>
        /// <param name="start">当前页</param>
        /// <param name="length">分页大小</param>
        /// <returns></returns>
        public async Task<IActionResult> GetTasks(int start, int length)
        {
            var jobs = await _scheduler.GetAllJobAsync();

            var list = jobs.OrderBy(n => n.JobGroup).ThenBy(n => n.JobName).Skip(start).Take(length);


            Dictionary<string, object> dic = new Dictionary<string, object>
            {
                { "recordsTotal",jobs.Count},
                { "recordsFiltered", jobs.Count},
                { "list", list }
            };
            return Json(dic);
        }

        /// <summary>
        /// 查询详细
        /// </summary>
        public async Task<IActionResult> GetTaskDetail(NameGroupModel nameGroupModel)
        {
            var jobKey = new JobKey(nameGroupModel.Name, nameGroupModel.Group);

            var job = await _scheduler.QueryScheduleAsync(jobKey);

            return Json(new ExecutionResult { Code = MessageCode.Success, Data = job });
        }

        /// <summary>
        /// 添加任务
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> AddTask(Schedule entity)
        {
            try
            {
                var result = await _scheduler.AddScheduleAsync(entity);

                return Json(result);
            }
            catch (Exception ex)
            {

                return Json(new ExecutionResult { Code = MessageCode.Failure, Message = ex.Message });
            }
        }

        /// <summary>
        /// 修改任务(移除后再添加)
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> ModifyTask(Schedule entity)
        {
            try
            {
                //if (await _scheduler.CheckTriggerExist(entity.JobGroup, entity.JobName))
                //{
                //    return Json(await _scheduler.RescheduleJobAsync(entity));
                //}
                //else
                //{
                if ((await _scheduler.PauseJobAsync(entity.JobGroup, entity.JobName)).Code == MessageCode.Success)
                    if ((await _scheduler.RemoveJobAsync(entity.JobGroup, entity.JobName)).Code == MessageCode.Success)
                        if ((await _scheduler.AddScheduleAsync(entity)).Code == MessageCode.Success)
                            return Json(new ExecutionResult { Code = MessageCode.Success, Message = "修改成功" });

                return Json(new ExecutionResult { Code = MessageCode.Failure, Message = "修改失败" });
                //}
            }
            catch (Exception ex)
            {

                return Json(new ExecutionResult { Code = MessageCode.Failure, Message = ex.Message });
            }
        }

        /// <summary>
        /// 停止任务
        /// </summary>
        public async Task<IActionResult> StopTask(NameGroupModel nameGroupModel)
        {
            var result = await _scheduler.PauseJobAsync(nameGroupModel.Group, nameGroupModel.Name);

            return Json(result);
        }

        /// <summary>
        /// 恢复任务
        /// </summary>
        public async Task<IActionResult> ResumeTask(NameGroupModel nameGroupModel)
        {
            var result = await _scheduler.ResumeJobAsync(nameGroupModel.Group, nameGroupModel.Name);

            return Json(result);
        }
        /// <summary>
        /// 删除任务
        /// </summary>
        public async Task<IActionResult> DeleteTask(NameGroupModel nameGroupModel)
        {
            var result = await _scheduler.RemoveJobAsync(nameGroupModel.Group, nameGroupModel.Name);

            try
            {
                var deleteHistories = _dbContext.ScheduleHistories.Where(n => n.JobName == nameGroupModel.Name && n.JobGroup == nameGroupModel.Group).ToList();

                foreach (var item in deleteHistories)
                {
                    _dbContext.Remove(item);
                }
                await _dbContext.SaveChangesAsync();
            }
            catch
            {

            }

            return Json(result);

        }


    }
}

